
import MenuToggle from '../components/MenuToggle';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import React, { useState } from 'react';
import { DialogContent, DialogTitle, DialogFooter, Dialog, DialogHeader, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { UserCheck, Shield, MoreVertical, EyeOff, Upload, Edit, Users, Eye, Trash2, Filter, Search, Plus, Download, Settings } from 'lucide-react';
import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuContent, DropdownMenu } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
const RoleManagement = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedRoles, setSelectedRoles] = useState([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [filterStatus, setFilterStatus] = useState('all');

  // 模拟角色数据
  const [roles, setRoles] = useState([
    {
      id: 1,
      name: '超级管理员',
      code: 'super_admin',
      description: '拥有系统所有权限，可以管理所有功能模块',
      status: 'active',
      userCount: 2,
      permissions: ['user_management', 'role_management', 'menu_config', 'system_settings'],
      createTime: '2024-01-01',
      updateTime: '2024-01-15'
    },
    {
      id: 2,
      name: '管理员',
      code: 'admin',
      description: '拥有大部分管理权限，可以管理用户和内容',
      status: 'active',
      userCount: 5,
      permissions: ['user_management', 'content_management', 'file_management'],
      createTime: '2024-01-02',
      updateTime: '2024-01-14'
    },
    {
      id: 3,
      name: '编辑者',
      code: 'editor',
      description: '可以编辑和管理内容，但不能管理用户',
      status: 'active',
      userCount: 12,
      permissions: ['content_management', 'file_management'],
      createTime: '2024-01-03',
      updateTime: '2024-01-13'
    },
    {
      id: 4,
      name: '普通用户',
      code: 'user',
      description: '基础用户权限，只能查看和使用基本功能',
      status: 'active',
      userCount: 45,
      permissions: ['file_view', 'profile_edit'],
      createTime: '2024-01-04',
      updateTime: '2024-01-12'
    },
    {
      id: 5,
      name: '访客',
      code: 'guest',
      description: '临时访问权限，功能受限',
      status: 'inactive',
      userCount: 0,
      permissions: ['file_view'],
      createTime: '2024-01-05',
      updateTime: '2024-01-11'
    }
  ]);

  const [newRole, setNewRole] = useState({
    name: '',
    code: '',
    description: '',
    status: 'active',
    permissions: []
  });

  // 权限选项
  const permissionOptions = [
    { id: 'user_management', name: '用户管理', description: '管理系统用户' },
    { id: 'role_management', name: '角色管理', description: '管理用户角色' },
    { id: 'menu_config', name: '菜单配置', description: '配置系统菜单' },
    { id: 'system_settings', name: '系统设置', description: '系统配置管理' },
    { id: 'content_management', name: '内容管理', description: '管理系统内容' },
    { id: 'file_management', name: '文件管理', description: '管理文件系统' },
    { id: 'file_view', name: '文件查看', description: '查看文件权限' },
    { id: 'profile_edit', name: '个人资料', description: '编辑个人信息' }
  ];

  // 过滤角色数据
  const filteredRoles = roles.filter(role => {
    const matchesSearch = role.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         role.code.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         role.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || role.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const handleRoleSelect = (roleId) => {
    setSelectedRoles(prev => 
      prev.includes(roleId) 
        ? prev.filter(id => id !== roleId)
        : [...prev, roleId]
    );
  };

  const handleSelectAll = () => {
    if (selectedRoles.length === filteredRoles.length) {
      setSelectedRoles([]);
    } else {
      setSelectedRoles(filteredRoles.map(role => role.id));
    }
  };

  const handleAddRole = () => {
    const id = Math.max(...roles.map(r => r.id)) + 1;
    const currentTime = new Date().toISOString().split('T')[0];
    
    setRoles(prev => [...prev, {
      ...newRole,
      id,
      userCount: 0,
      createTime: currentTime,
      updateTime: currentTime
    }]);
    
    setNewRole({
      name: '',
      code: '',
      description: '',
      status: 'active',
      permissions: []
    });
    setShowAddDialog(false);
  };

  const handleEditRole = (role) => {
    setEditingRole(role);
    setShowEditDialog(true);
  };

  const handleUpdateRole = () => {
    setRoles(prev => prev.map(role => 
      role.id === editingRole.id ? {
        ...editingRole,
        updateTime: new Date().toISOString().split('T')[0]
      } : role
    ));
    setShowEditDialog(false);
    setEditingRole(null);
  };

  const handleDeleteRole = (roleId) => {
    setRoles(prev => prev.filter(role => role.id !== roleId));
    setSelectedRoles(prev => prev.filter(id => id !== roleId));
  };

  const handleBatchDelete = () => {
    setRoles(prev => prev.filter(role => !selectedRoles.includes(role.id)));
    setSelectedRoles([]);
  };

  const handleToggleStatus = (roleId) => {
    setRoles(prev => prev.map(role => 
      role.id === roleId ? {
        ...role,
        status: role.status === 'active' ? 'inactive' : 'active',
        updateTime: new Date().toISOString().split('T')[0]
      } : role
    ));
  };

  const getStatusBadge = (status) => {
    return status === 'active' ? (
      <Badge className="bg-green-100 text-green-800 hover:bg-green-100">
        启用
      </Badge>
    ) : (
      <Badge variant="secondary" className="bg-red-100 text-red-800 hover:bg-red-100">
        禁用
      </Badge>
    );
  };

  const getPermissionName = (permissionId) => {
    const permission = permissionOptions.find(p => p.id === permissionId);
    return permission ? permission.name : permissionId;
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-primary to-primary-600 rounded-xl flex items-center justify-center">
                  <UserCheck className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    角色管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理系统角色和权限配置
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline" size="default">
                <Download className="w-4 h-4 mr-2" />
                导出
              </Button>
              
              <Button variant="outline" size="default">
                <Upload className="w-4 h-4 mr-2" />
                导入
              </Button>

              <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
                <DialogTrigger asChild>
                  <Button className="bg-gradient-to-r from-primary to-primary-600 hover:from-primary-600 hover:to-primary-700">
                    <Plus className="w-4 h-4 mr-2" />
                    新增角色
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-lg">
                  <DialogHeader>
                    <DialogTitle>新增角色</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4 max-h-96 overflow-y-auto">
                    <div>
                      <Label htmlFor="name">角色名称</Label>
                      <Input
                        id="name"
                        value={newRole.name}
                        onChange={(e) => setNewRole(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="请输入角色名称"
                      />
                    </div>
                    <div>
                      <Label htmlFor="code">角色代码</Label>
                      <Input
                        id="code"
                        value={newRole.code}
                        onChange={(e) => setNewRole(prev => ({ ...prev, code: e.target.value }))}
                        placeholder="请输入角色代码，如 admin"
                      />
                    </div>
                    <div>
                      <Label htmlFor="description">角色描述</Label>
                      <Textarea
                        id="description"
                        value={newRole.description}
                        onChange={(e) => setNewRole(prev => ({ ...prev, description: e.target.value }))}
                        placeholder="请输入角色描述"
                        rows={3}
                      />
                    </div>
                    <div>
                      <Label>权限配置</Label>
                      <div className="mt-2 space-y-2 max-h-40 overflow-y-auto border rounded-md p-3">
                        {permissionOptions.map(permission => (
                          <div key={permission.id} className="flex items-center space-x-2">
                            <input
                              type="checkbox"
                              id={`new-${permission.id}`}
                              checked={newRole.permissions.includes(permission.id)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setNewRole(prev => ({
                                    ...prev,
                                    permissions: [...prev.permissions, permission.id]
                                  }));
                                } else {
                                  setNewRole(prev => ({
                                    ...prev,
                                    permissions: prev.permissions.filter(p => p !== permission.id)
                                  }));
                                }
                              }}
                              className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                            />
                            <div>
                              <label htmlFor={`new-${permission.id}`} className="text-sm font-medium text-material-grey-900 cursor-pointer">
                                {permission.name}
                              </label>
                              <p className="text-xs text-material-grey-500">{permission.description}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setShowAddDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={handleAddRole}>
                      确认添加
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总角色数</p>
                  <p className="text-2xl font-bold text-material-grey-900">{roles.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <UserCheck className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">启用角色</p>
                  <p className="text-2xl font-bold text-green-600">
                    {roles.filter(r => r.status === 'active').length}
                  </p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <Shield className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">关联用户</p>
                  <p className="text-2xl font-bold text-purple-600">
                    {roles.reduce((sum, role) => sum + role.userCount, 0)}
                  </p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Users className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">权限总数</p>
                  <p className="text-2xl font-bold text-orange-600">{permissionOptions.length}</p>
                </div>
                <div className="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                  <Settings className="w-6 h-6 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 搜索和筛选 */}
        <Card className="mb-6">
          <CardContent className="p-6">
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <Input
                  placeholder="搜索角色名称、代码或描述..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                />
              </div>
              
              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-full sm:w-48">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">启用</SelectItem>
                  <SelectItem value="inactive">禁用</SelectItem>
                </SelectContent>
              </Select>

              {selectedRoles.length > 0 && (
                <Button 
                  variant="destructive" 
                  onClick={handleBatchDelete}
                  className="w-full sm:w-auto"
                >
                  <Trash2 className="w-4 h-4 mr-2" />
                  批量删除 ({selectedRoles.length})
                </Button>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 角色列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">
                    <input
                      type="checkbox"
                      checked={selectedRoles.length === filteredRoles.length && filteredRoles.length > 0}
                      onChange={handleSelectAll}
                      className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                    />
                  </TableHead>
                  <TableHead>角色信息</TableHead>
                  <TableHead>权限数量</TableHead>
                  <TableHead>关联用户</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>更新时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredRoles.map((role) => (
                  <TableRow key={role.id}>
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedRoles.includes(role.id)}
                        onChange={() => handleRoleSelect(role.id)}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center space-x-3">
                          <div className="w-10 h-10 bg-gradient-to-br from-primary/20 to-primary/30 rounded-lg flex items-center justify-center">
                            <UserCheck className="w-5 h-5 text-primary" />
                          </div>
                          <div>
                            <p className="font-medium text-material-grey-900">{role.name}</p>
                            <p className="text-sm text-material-grey-500">代码: {role.code}</p>
                          </div>
                        </div>
                        <p className="text-sm text-material-grey-600 ml-13">{role.description}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <span className="text-sm font-medium text-material-grey-900">
                          {role.permissions.length} 个权限
                        </span>
                        <div className="flex flex-wrap gap-1">
                          {role.permissions.slice(0, 3).map(permission => (
                            <Badge key={permission} variant="secondary" className="text-xs">
                              {getPermissionName(permission)}
                            </Badge>
                          ))}
                          {role.permissions.length > 3 && (
                            <Badge variant="secondary" className="text-xs">
                              +{role.permissions.length - 3}
                            </Badge>
                          )}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <Users className="w-4 h-4 text-material-grey-500" />
                        <span className="text-sm text-material-grey-700">{role.userCount} 人</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(role.status)}
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-600">{role.updateTime}</span>
                    </TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => handleEditRole(role)}>
                            <Edit className="w-4 h-4 mr-2" />
                            编辑
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleToggleStatus(role.id)}>
                            {role.status === 'active' ? (
                              <>
                                <EyeOff className="w-4 h-4 mr-2" />
                                禁用
                              </>
                            ) : (
                              <>
                                <Eye className="w-4 h-4 mr-2" />
                                启用
                              </>
                            )}
                          </DropdownMenuItem>
                          <DropdownMenuItem 
                            onClick={() => handleDeleteRole(role.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredRoles.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <UserCheck className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的角色' : '暂无角色数据'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '点击上方按钮开始添加角色'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 编辑角色对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>编辑角色</DialogTitle>
          </DialogHeader>
          {editingRole && (
            <div className="space-y-4 max-h-96 overflow-y-auto">
              <div>
                <Label htmlFor="edit-name">角色名称</Label>
                <Input
                  id="edit-name"
                  value={editingRole.name}
                  onChange={(e) => setEditingRole(prev => ({ ...prev, name: e.target.value }))}
                />
              </div>
              <div>
                <Label htmlFor="edit-code">角色代码</Label>
                <Input
                  id="edit-code"
                  value={editingRole.code}
                  onChange={(e) => setEditingRole(prev => ({ ...prev, code: e.target.value }))}
                />
              </div>
              <div>
                <Label htmlFor="edit-description">角色描述</Label>
                <Textarea
                  id="edit-description"
                  value={editingRole.description}
                  onChange={(e) => setEditingRole(prev => ({ ...prev, description: e.target.value }))}
                  rows={3}
                />
              </div>
              <div>
                <Label>权限配置</Label>
                <div className="mt-2 space-y-2 max-h-40 overflow-y-auto border rounded-md p-3">
                  {permissionOptions.map(permission => (
                    <div key={permission.id} className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id={`edit-${permission.id}`}
                        checked={editingRole.permissions.includes(permission.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setEditingRole(prev => ({
                              ...prev,
                              permissions: [...prev.permissions, permission.id]
                            }));
                          } else {
                            setEditingRole(prev => ({
                              ...prev,
                              permissions: prev.permissions.filter(p => p !== permission.id)
                            }));
                          }
                        }}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                      <div>
                        <label htmlFor={`edit-${permission.id}`} className="text-sm font-medium text-material-grey-900 cursor-pointer">
                          {permission.name}
                        </label>
                        <p className="text-xs text-material-grey-500">{permission.description}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="edit-status"
                  checked={editingRole.status === 'active'}
                  onCheckedChange={(checked) => setEditingRole(prev => ({ 
                    ...prev, 
                    status: checked ? 'active' : 'inactive' 
                  }))}
                />
                <Label htmlFor="edit-status">启用角色</Label>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditDialog(false)}>
              取消
            </Button>
            <Button onClick={handleUpdateRole}>
              保存更改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default RoleManagement;
